package client;
/**
 * The client simulator
 * 
 * @author Syed Rizvi, Denis Zgonjanin
 */

import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;

public class Client {
	   private BufferedReader in;
	   private PrintWriter out;
	   public ArrayList<Thread> threads;
	   public static String log = "";
	   
	   public static final String IP = "127.0.0.1";
	   public static final int PORT = 1026;

	   /**
	    * The default constructor
	    */
	   public Client()
	   {
		   threads = new ArrayList<Thread>();
	   }
	   
	   public static void logger(String log){
		   PrintWriter logger = null;
		   try{
			   logger = new PrintWriter(new FileWriter("log.txt"));
			   logger.print(log);
		   } catch(Exception e){
			   System.out.println(e.getMessage());
		   } finally{
			   if (logger!= null) logger.close();
		   }
	   }
	   
	   /**
	    * Closes the Client
	    */
	   public void close()
	   {
		   logger(log);
		   try {
			   if (out!= null) out.close();
			   if (in!= null) in.close(); 
		   } catch (IOException e) { 
			   System.err.println(e.getMessage());
	           System.exit(1);
		   }	   
	   }
	   
	   /**
	    * Loads the test script from a file
	    * @param file The file containing the tests
	    * @return
	    */
	   public ArrayList<String> loadTestScript(String file){
			ArrayList<String> list = new ArrayList<String>();
			BufferedReader inputStream = null;
			String test = "";
			
			try{ //Try to read the file
				inputStream = new BufferedReader(new FileReader(file));
				String l;
	            while ((l = inputStream.readLine()) != null) {
	            	test = test.concat(l) + "\n";
	            }
			} catch (Exception e){
				System.out.println(e.getMessage());
			} finally{ //Close the file, just to be safe
				if (inputStream != null){
					try{
						inputStream.close();
					} catch (Exception e) {
						System.out.println(e.getMessage());
					}
				}
			}
			//Parse the string into separate HTTP requests, and add them to an ArrayList
			String[] t = test.split("\n\n");
			for (String s:t) list.add(s);
			return list;
		}
	   
	   /**
	    * The main method. Starts the application
	    * @param args
	    */
	   public static void main(String args[])
	   {
		   Client c = new Client();
	      
		   System.out.print("Enter script file name:");
		   Scanner in = new Scanner(System.in);
		   String fileName = in.nextLine();
		   ArrayList<String> testList = c.loadTestScript(fileName);
		   
		   for (String request:testList){
			   Thread req = new Thread(new RequestThread(IP, PORT, request));
			   c.threads.add(req);
			   req.start();
		   }

		   try{
			   for (Thread http:c.threads)  http.join();
		   } catch (InterruptedException e){
			   System.out.println(e.getMessage());
		   }
			   
		   //c.close();
	   }
	   
}